package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.damain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Page<Address> findone(Integer pageNum, Integer pageSize) {
        return null;
    }

    //增加地址
    @Override
    public void save(Address address) {
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0);//默认地址为1，非默认为0
        //保存
        addressMapper.insert(address);
    }
//查询当前id所有地址
    @Override
    public List<Address> select() {
        //获取当前id
        LambdaQueryWrapper<Address>wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        List<Address>list=addressMapper.selectList(wrapper);
        return list;
    }
//设置默认地址
    @Override
    public void defaut(Long id) {
        Address address = new Address();
        address.setIsDefault(0);
        LambdaQueryWrapper<Address>wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,UserHolder.get().getId());
        addressMapper.update(address,wrapper);
//        Address address=new Address();
//        address.setIsDefault(0);
//        addressMapper.update(address,wrapper);
//
        Address address1 = new Address();
        address1.setId(id);
        address1.setIsDefault(1);
        addressMapper.updateById(address1);
    }
//主键查询
    @Override
    public Address findbyid(Long id) {
       return addressMapper.selectById(id);

    }
//更新
    @Override
    public void update(Address address) {
        addressMapper.updateById(address);
    }
//删除
    @Override
    public void delete(List<Long> id) {
        addressMapper.deleteBatchIds(id);

    }
//查询默认地址
    @Override
    public Address getdefaut() {
       LambdaQueryWrapper<Address>wrapper=new LambdaQueryWrapper<>();
       wrapper.eq(Address::getUserId,UserHolder.get().getId())
               .eq(Address::getIsDefault,1);
       return addressMapper.selectOne(wrapper);

    }

}
